package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/admin/product")
public class FileController {

    @Value("${img.url}")
    private String imgUrl;

    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file){
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        System.out.println(file.getName());
        //获取配置文件全路径
        String path = ClassUtils.getDefaultClassLoader().getResource("fdfs_client.conf").getPath();
        try {
            //通过配置文件构建全局配置
            ClientGlobal.init(path);
            TrackerClient trackerClient = new TrackerClient();
            //连接Tracker
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = null;
            //连接存储节点
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            //文件的扩展名
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            //上传图片
            String p = storageClient1.upload_file1(file.getBytes(), ext, null);
            System.out.println(p);
            return Result.ok(imgUrl + p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return null;
    }

}
